<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use Carbon\Carbon;
use App\Console\Commands\WdtClient;

// 销售出库单查询定时任务 5min一次
// 执行命令: php artisan sync:StockoutOrderQueryTrade
// 接口描述：获取旺店通ERP销售订单的出库单信息
// 文档地址: https://open.wangdian.cn/qyb/open/apidoc/doc?path=stockout_order_query_trade.php


//已创建定时任务 StockoutOrderQueryTrade.php，实现如下：
//每10分钟同步一次旺店通销售出库单（接口 stockout_order_query_trade.php）。
//查询时间区间为当前时间往前推11分钟，防止遗漏。
//分页拉取，每页50条，自动翻页。
//只处理已发货（95）和已完成（110）状态的出库单。
//匹配本地表 e_store_order 的 order_sn 字段，若存在则更新：
//rec_id 字段为源单号 src_order_no
//send_status 字段（2=已发货，3=已收货，1=待发货）
//updated_at 时间戳

class StockoutOrderQueryTrade extends Command
{
    protected $signature = 'sync:StockoutOrderQueryTrade';
    protected $description = '同步旺店通销售出库单信息到本地订单表';

    // 每10分钟同步一次，时间跨度需衔接，避免遗漏
    public function handle()
    {
        Log::info('StockoutOrderQueryTrade', ['开始同步销售出库单']);
        $sid = config('services.wdt.sid');
        $appKey = config('services.wdt.appkey');
        $secret = config('services.wdt.secret');
        $url = config('services.wdt.url') . 'stockout_order_query_trade.php';
        $shopNo = config('services.wdt.shopNo');
        $c = new WdtClient($sid, $appKey, $secret, $url);

        // 计算时间区间，避免遗漏和重复
        $now = Carbon::now();
        $endTime = $now->copy()->subMinutes(3)->format('Y-m-d H:i:s'); // 当前时间-3分钟
        $startTime = $now->copy()->subMinutes(14)->format('Y-m-d H:i:s'); // 往前推14分钟

        $pageSize = 100; //本地测试的时候修改为1 不要让订单消耗过快
        $this->syncStockoutOrders($c, $shopNo, $startTime, $endTime, $pageSize);
        $this->info('StockoutOrderQueryTrade任务执行完毕');
    }

    /**
     * 分页同步销售出库单
     */
    private function syncStockoutOrders($client, $shopNo, $startTime, $endTime, $pageSize)
    {
        $pageNo = 0;
        $totalCount = null;
        do {
            $requestParams = [
                'start_time' => $startTime,
                'end_time' => $endTime,
                'page_no' => $pageNo,
                'page_size' => $pageSize,
                'shop_no' => $shopNo,
                'status' => 95,
            ];
            Log::info('StockoutOrderQueryTrade 请求参数', $requestParams);
            $client->putApiParam('start_time', $startTime);
            $client->putApiParam('end_time', $endTime);
            $client->putApiParam('page_no', $pageNo);
            $client->putApiParam('page_size', $pageSize);
            $client->putApiParam('shop_no', $shopNo);
            $client->putApiParam('status', 95);

            $result = $client->wdtOpenApi();
            $resultArr = json_decode($result, true);
            Log::info('StockoutOrderQueryTrade result', [$resultArr]);
            if (!isset($resultArr['code']) || $resultArr['code'] != 0) {
                Log::error('StockoutOrderQueryTrade error', [$resultArr]);
                break;
            }
            if ($pageNo === 0 && isset($resultArr['total_count'])) {
                $totalCount = (int)$resultArr['total_count'];
            }
            $stockoutList = $resultArr['stockout_list'] ?? [];
            if (empty($stockoutList)) {
                break;
            }
            $this->processStockoutList($stockoutList);
            $pageNo++;
            // 计算是否还有下一页
            $hasMore = $totalCount !== null ? ($pageNo * $pageSize < $totalCount) : (count($stockoutList) >= $pageSize);
        } while ($hasMore);
    }

    /**
     * 处理单页出库单数据
     */
    private function processStockoutList($stockoutList)
    {
        foreach ($stockoutList as $stockout) {
            $trade_id= $stockout['trade_id'] ?? '';
            $srcOrderNo = $stockout['src_order_no'] ?? '';
            $tradeStatus = $stockout['trade_status'] ?? 0;
            if (!$trade_id) continue;
            // 匹配本地订单
            $order = DB::table('store_order')->where('trade_id', $trade_id)->first();
            if ($order) {
                // 订单状态映射：95=已发货, 110=已完成, 其他不处理
                $sendStatus = 1; // 默认待发货
                if ($tradeStatus == 95) {
                    $sendStatus = 2; // 已发货
                } elseif ($tradeStatus == 110) {
                    $sendStatus = 3; // 已收货
                }
                // 更新src_order_no和发货状态
                DB::table('store_order')->where('trade_id', $trade_id)->update([
                    'src_order_no' => $srcOrderNo,//旺店通订单号
                    'send_status' => $sendStatus,
                    'updated_at' => time(),
                ]);
            }
        }
    }
} 